package com.edou.cms.controller.admin;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.edou.base.controller.BaseController;
import com.edou.cms.entity.CmsChannel;
import com.edou.cms.form.CmsChannelForm;
import com.edou.cms.service.ICmsArticleService;
import com.edou.cms.service.ICmsChannelService;

/**
 * 
 * 栏目管理
 * 
 * @author 欧阳明航
 *
 */
@Controller("articleChannelAdminController")
@Scope("prototype")
@RequestMapping(value = "/admin/cms/channel")
public class ArticleChannelAdminController extends BaseController {

	private Log logger = LogFactory.getLog(CmsChannel.class);

	@Resource
	private ICmsChannelService channelService;

	@Resource
	private ICmsArticleService cmsArticleService;

	@RequestMapping(value = "/index.htm", method = RequestMethod.GET)
	public ModelAndView home(CmsChannelForm model) {
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/cms/channel_list");
		return view;
	}

	/**
	 * 分页查询文章
	 */
	@RequestMapping(value = "/searchCmsChannelList.htm", method = RequestMethod.POST)
	public void searchCmsChannelList(@ModelAttribute CmsChannelForm cmsChannelForm, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			channelService.getChannelListByPage(cmsChannelForm.getPageResult());
			JSONObject root = toPageJson(cmsChannelForm.getPageResult(),
					new String[] { "id", "name", "remark", "state", "isRight", "sort" });
			ajaxPageResult(root, response);
		} catch (Exception ex) {
			String msg = "查询文章时发生异常：" + ex.getMessage();
			logger.error(msg, ex);
			ajaxJSON(Status.error, "查询失败");
		}
	}

	@RequestMapping(value = "/toAddCategory.htm", method = RequestMethod.GET)
	public ModelAndView toAddCategory(CmsChannelForm model) {
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/cms/channel_add");
		Map<String, Object> data = view.getModel();
		data.put("parentId", model.getParentId());
		return view;
	}

	/*
	 * 新增商品类别
	 */
	@RequestMapping(value = "/doAddCmsChannel.htm", method = RequestMethod.POST)
	public ModelAndView doAddCmsChannel(@ModelAttribute CmsChannelForm cmsChannelForm, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			// 上级类别ID
			String parentId = cmsChannelForm.getParentId();

			// 上级类别ID
			if (StringUtils.isBlank(parentId)) {
				return ajaxJSON(Status.error, "父类ID不能为空");
			}
			// 类别名称
			String name = cmsChannelForm.getName();
			if (StringUtils.isBlank(name)) {
				return ajaxJSON(Status.error, "类别名称不能为空");
			}
			// 排序
			Integer sort = cmsChannelForm.getSortNum() == null ? 0 : cmsChannelForm.getSortNum();

			// 参数 节点ID，类别名称，备注，序号
			channelService.doAddCmsChannel(parentId, name, cmsChannelForm.getRemark(), sort);
			return ajaxJSON(Status.success, "新增商品类别成功");
		} catch (Exception ex) {
			String msg = "新增商品类别时发生异常：" + ex.getMessage();
			logger.error(msg, ex);
			return ajaxJSON(Status.error, "新增商品类别失败");
		}
	}

	@RequestMapping(value = "/toUpdateCmsChannel.htm", method = RequestMethod.GET)
	public ModelAndView toUpdateCmsChannel(@ModelAttribute CmsChannelForm model) {
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/cms/channel_add");
		Map<String, Object> data = view.getModel();

		// 获得类别的ID
		String nodeId = model.getNodeid();
		// 获得类别信息
		CmsChannel item = channelService.getById(nodeId);
		data.put("item", item);
		data.put("nodeid", model.getNodeid());
		return view;
	}

	/*
	 * 修改商品类别
	 */
	@RequestMapping(value = "/doUpdateCmsChannel.htm", method = RequestMethod.POST)
	public ModelAndView doUpdateCmsChannel(@ModelAttribute CmsChannelForm cmsChannelForm, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			// 节点ID
			if (StringUtils.isBlank(cmsChannelForm.getNodeid())) {
				return ajaxJSON(Status.error, "修改失败");
			}
			// 类别名称
			if (StringUtils.isBlank(cmsChannelForm.getName())) {
				return ajaxJSON(Status.error, "类别名称不能为空。");
			}
			// 排序
			Integer sort = cmsChannelForm.getSortNum() == null ? 0 : cmsChannelForm.getSortNum();

			// 参数 节点ID，类别名称，备注，序号
			channelService.doUpdateCmsChannel(cmsChannelForm.getNodeid(), cmsChannelForm.getName(),
					cmsChannelForm.getRemark(), sort);
			return ajaxJSON(Status.success, "修改成功。");
		} catch (Exception ex) {
			String msg = "修改商品类别时发生异常：" + ex.getMessage();
			logger.error(msg, ex);
			return ajaxJSON(Status.error, "修改商品类别失败");
		}
	}

	/*
	 * 删除商品类别
	 */
	@RequestMapping(value = "/delCmsChannelById.htm", method = RequestMethod.POST)
	public ModelAndView delCmsChannelById(@ModelAttribute CmsChannelForm cmsChannelForm, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			String id = cmsChannelForm.getNodeid();
			if (StringUtils.isBlank(id)) {
				return ajaxJSON(Status.error, "类别ID不能为空");
			} else {
				CmsChannel channel = channelService.getById(id);

				// 删除标记位
				if (null != channel && channel.getIsDelete() != null && channel.getIsDelete().intValue() == 1) {
					return ajaxJSON(Status.error, "该类别不可删除");
				} else {
					// 系统与用户
					if (null != channel && channel.getState() != null && channel.getState().intValue() == 1) {
						return ajaxJSON(Status.error, "该类别不可删除");
					} else {
						channelService.delCmsChannel(channel);
						return ajaxJSON(Status.success, "删除商品类别成功");
					}
				}
			}
		} catch (Exception ex) {
			String msg = "删除商品类别时发生异常：" + ex.getMessage();
			logger.error(msg, ex);
			return ajaxJSON(Status.error, "删除商品类别失败");
		}
	}

	/*
	 * 保存栏目
	 */
	@RequestMapping(value = "/doSave.htm", method = RequestMethod.POST)
	public ModelAndView doSave(@ModelAttribute CmsChannelForm cmsChannelForm, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			if (StringUtils.isBlank(cmsChannelForm.getItem().getName())) {
				return ajaxJSON(Status.error, "栏目标题不能为空");
			} else {
				channelService.doSave(cmsChannelForm.getItem());
				return ajaxJSON(Status.success, "保存成功");
			}
		} catch (Exception ex) {
			String msg = "保存栏目时发生异常：" + ex.getMessage();
			logger.error(msg, ex);
			return ajaxJSON(Status.error, "保存栏目失败");
		}
	}

	/*
	 * 删除产品栏目
	 */
	@RequestMapping(value = "/delChannel.htm", method = RequestMethod.POST)
	public ModelAndView delChannel(@ModelAttribute CmsChannelForm cmsChannelForm, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			if (StringUtils.isBlank(cmsChannelForm.getChannelId())) {
				return ajaxJSON(Status.error, "栏目ID不能为空!");
			} else {
				int count = cmsArticleService.getArticleCount(cmsChannelForm.getChannelId());
				if (count > 0) {
					return ajaxJSON(Status.error, "该栏目下有文章，无法删除！");
				} else {
					channelService.delChannel(cmsChannelForm.getChannelId());
					return ajaxJSON(Status.success, "删除成功!");
				}
			}
		} catch (Exception ex) {
			String msg = "删除产品栏目时发生异常：" + ex.getMessage();
			logger.error(msg, ex);
			return ajaxJSON(Status.error, "删除产品栏目失败");
		}
	}

	/*
	 * 显示右边产品栏目
	 */
	@RequestMapping(value = "/showRight.htm", method = RequestMethod.POST)
	public ModelAndView showRight(@ModelAttribute CmsChannelForm cmsChannelForm, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			if (StringUtils.isBlank(cmsChannelForm.getChannelId())) {
				return ajaxJSON(Status.error, "栏目ID不能为空!");
			} else {
				channelService.showRight(cmsChannelForm.getChannelId());
				return ajaxJSON(Status.success, "显示右边产品栏目成功!");
			}
		} catch (Exception ex) {
			String msg = "显示右边产品栏目时发生异常：" + ex.getMessage();
			logger.error(msg, ex);
			return ajaxJSON(Status.error, "显示右边产品栏目失败");
		}
	}

	/*
	 * 不显示右边产品栏目
	 */
	@RequestMapping(value = "/unShowRight.htm", method = RequestMethod.POST)
	public ModelAndView unShowRight(@ModelAttribute CmsChannelForm cmsChannelForm, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			if (StringUtils.isBlank(cmsChannelForm.getChannelId())) {
				return ajaxJSON(Status.error, "栏目ID不能为空!");
			} else {
				channelService.unShowRight(cmsChannelForm.getChannelId());
				return ajaxJSON(Status.success, "不显示右边产品栏目成功!");
			}
		} catch (Exception ex) {
			String msg = "不显示右边产品栏目时发生异常：" + ex.getMessage();
			logger.error(msg, ex);
			return ajaxJSON(Status.error, "不显示右边产品栏目失败");
		}
	}
	
	/*
	 * 显示栏目树，默认展开第一级
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/list_channel.htm", method = RequestMethod.POST)
	public ModelAndView listChannelFirst(@ModelAttribute CmsChannelForm cmsChannelForm, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			JSONArray channels = new JSONArray();
			// 加载全部
			if (StringUtils.isBlank(cmsChannelForm.getParentId())) {
				JSONObject root = buildRoot();
				buildChildrenChannels(root);
				channels.add(root);
			} else {
				// 点击后加载
				List<CmsChannel> childrenChannels = channelService.listChannelByPid(cmsChannelForm.getParentId());
				for (CmsChannel cmsChannel : childrenChannels) {
					channels.add(buildJsonObject(cmsChannel));
				}
			}
			return ajaxJSON(Status.success, "显示栏目树成功", channels);
		} catch (Exception ex) {
			String msg = "显示栏目树时发生异常：" + ex.getMessage();
			logger.error(msg, ex);
			return ajaxJSON(Status.error, "显示栏目树失败");
		}

	}
	
	/**
	 * 栏目排序，适用于树的拖拽功能
	 * @param cmsChannelForm
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/doSortByDragTreeNode.htm", method = RequestMethod.POST)
	public ModelAndView doSortByDragTreeNode(@ModelAttribute CmsChannelForm model, HttpServletRequest request,HttpServletResponse response) {
		try{
			String selIds = model.getSelIds();
			if(StringUtils.isBlank(selIds)){
				return ajaxJSON(Status.error,"排序失败，未传入排序数据"); 
			}
			
			//进行排序
			channelService.doSortByDragTreeNode(selIds.split(","));
			
			return ajaxJSON(Status.success,"排序成功");
			
		}catch(Exception ex){
			String msg = "拖拽树节点进行排序发生异常：" + ex.getMessage();
			logger.error(msg, ex);
			
			return ajaxJSON(Status.error,"排序失败，请稍后重试");
		}
	}
	
	// 获取“全部”
	private CmsChannel getRootChannel(){
		CmsChannel rootChannel =channelService.getById("0");
		if(rootChannel == null){
			rootChannel = new CmsChannel();
			rootChannel.setId("0");
			rootChannel.setName("全部");
			rootChannel.setSort(0);
			rootChannel.setParent("-1");
			rootChannel.setIsDelete(1);
			rootChannel.setLevel(0);
			rootChannel.setState(1);
		}
		return rootChannel;
	}

	// 构造“全部”项
	@SuppressWarnings("unchecked")
	private JSONObject buildRoot() {
		JSONObject root = new JSONObject();
		CmsChannel rootChannel = getRootChannel();
		root.put("id", rootChannel.getId());
		root.put("name", rootChannel.getName());
		root.put("sort", rootChannel.getSort());
		root.put("parentId", rootChannel.getIsParent());
		root.put("isDelete", rootChannel.getIsDelete());
		root.put("level", rootChannel.getLevel());
		root.put("state", rootChannel.getState());
		root.put("isParent", true);
		root.put("open", true);
		return root;
	}

	/*
	 * 制作树结构
	 */
	@SuppressWarnings("unchecked")
	private void buildChildrenChannels(JSONObject parent) {
		JSONArray children = new JSONArray();
		for (CmsChannel channel : channelService.listChannelByPid(parent.get("id").toString())) {
			JSONObject jsonChannel = buildJsonObject(channel);
			buildChildrenChannels(jsonChannel);
			children.add(jsonChannel);
		}
		parent.put("children", children);
	}

	@SuppressWarnings("unchecked")
	private JSONObject buildJsonObject(CmsChannel channel) {
		JSONObject data = new JSONObject();
		data.put("id", channel.getId());
		data.put("name", channel.getName());
		data.put("level", channel.getLevel());
		if (channel.getIsParent() != null && channel.getIsParent().intValue() == 1) {
			data.put("isParent", true);
		} else {
			data.put("isParent", false);
		}
		data.put("parentId", channel.getParent());
		data.put("isDelete", channel.getIsDelete());
		data.put("state", channel.getState());
		data.put("open", true);
		return data;
	}

}
